package com.multi.thread.chapter04.demo11;

import java.util.concurrent.locks.ReentrantLock;

/**
 *	lockInterruptibly():如果线程未被中断，则获取锁定，如果已经被中断则出现异常
 */
public class TestLockInterruptibly {
	
	private ReentrantLock lock = new ReentrantLock();
	
	public void waitMethod() {
		try {
			lock.lockInterruptibly();
			System.out.println("lock begin : " + Thread.currentThread().getName());
			for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
				Math.random();
			}
			System.out.println("lock  end: " + Thread.currentThread().getName());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			if (lock.isHeldByCurrentThread()) {
				lock.unlock();
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final TestLockInterruptibly service = new TestLockInterruptibly();
		Runnable run = new Runnable() {
			@Override
			public void run() {
				service.waitMethod();
			}
		};
		Thread a = new Thread(run);
		a.setName("A");
		a.start();
		Thread.sleep(500);
		Thread b = new Thread(run);
		b.setName("B");
		b.start();
		b.interrupt();
	}

}
